package com.bdqn.myInterceptor;

import com.bdqn.entity.UmsUser;
import com.bdqn.util.HttpUtils;
import com.bdqn.entity.util.RespBean;
import com.bdqn.entity.util.ResultEnum;
import com.bdqn.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(AuthorizationInterceptor.class);
    @Autowired
    private Pet_service_RedisTemplate pet_service_redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头的token
        String token = request.getHeader("token");
        logger.info("#################从header中得到token[" + token + "]#################");
        //判断请求头的token是否为空
        if (StringUtils.isEmpty(token)) {
            //token为空
            HttpUtils.outputJson(response, new RespBean(ResultEnum.AUTH_TOKEN_EMPTY));
            return false;
        } else {
            UmsUser userStr = pet_service_redisTemplate.getUser(token);
            logger.info("AuthorizationInterceptor-->获取到用户登录信息users:{}", userStr);
            if (StringUtils.isEmpty(userStr)) {
                //登录不成功
                HttpUtils.outputJson(response, new RespBean(ResultEnum.AUTH_USER_NOT_LOGIN));
                return false;
            } else {
                //登录成功
//           response.getWriter().print(ResultEnum.SUCCESS);
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
